<?php

namespace app\common\controller;

use app\api\controller\Auth;
use app\api\model\Agent;
use app\api\model\ServerUser;
use app\api\model\Token;
use app\api\model\User;
use app\BaseController;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\Model;
use think\Response;

/**
 * Class AdminController
 * @package app\common\controller
 */
class ApiController extends BaseController
{

    use \app\common\traits\JumpTrait;

    //token
    protected $token = '';
    //用户 id
    protected $uid = 0;

    protected $method = '';

    protected $u_type = 1;

    /**
     * 无需登录的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 需要登录的方法
     * @var array
     */
    protected $mustLogin = [];

    protected $auth = null;

    protected $responseType = 'json';

    /**
     * 允许修改的字段
     * @var array
     */
    protected $allowModifyFields = [
        'status',
        'sort',
        'remark',
        'is_delete',
        'is_auth',
        'status_text',
    ];

    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;

    /**
     * 不导出的字段信息
     * @var array
     */
    protected $noExportFields = ['delete_time', 'update_time'];

    /**
     * 初始化方法
     */
    protected function initialize()
    {

        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
        header("Access-Control-Allow-Headers:DNT,method,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
        $token = $this->request->header('token');
        $method = $this->request->header('method');

        $this->method = $method;

        $this->auth = Auth::instance();

        if (empty($method)) {
            $this->error('无权限！');
        }
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $is_token = Token::where('token', $token)->where('type', $method)->find();
            //dump($is_token);die;
            if (!$is_token) {
                $this->error('请先登录', null, 401);
            } else {
                $this->uid = $is_token['user_id'];
            }
            if (!$this->uid) {
                $this->error('请先登录', null, 401);
            }
            if ($method == 'server_user') {
              //  $userModel = new ServerUser();
              //  $block = $userModel->where('id', $this->uid)->value('block');
                $this->u_type = 2;
            }
            if ($method == 'app_user') {
                $userModel = new User();
                $block = Db::name('user_shopowner')->where('id', $this->uid)->value('status');
                $this->u_type = 1;
            }
            if ($method == 'agent_user') {
               // $userModel = new Agent();
                $block = $userModel->where('id', $this->uid)->value('block');
                $this->u_type = 3;
            }
            if ($block == 2) {
                $this->error('账号冻结，请联系平台处理', null, 402);
            }

            //     // 判断是否需要验证权限
            //     if (!$this->auth->match($this->noNeedRight)) {

            //         // // 判断控制器和方法判断是否有对应权限
            //         // if (!$this->auth->check($path)) {
            //         //     $this->error('没有权限', null, 403);
            //         // }
            //         if (!$this->uid) {
            //             $this->error('没有权限', null, 403);
            //         }
            //         // $userStatus = $this->userIsExit($this->uid, $method);
            //         $userStatus = '';
            //         if (!$userStatus) {
            //             $this->error('没有权限', null, 403);
            //         }
            //         if ($userStatus['status'] != 1) {
            //             $this->error('账号异常，请联系客服处理', null, 403);
            //         }
            //         if (!$userStatus['wx_openid']) {
            //             $this->error('需要授权登录', null, 201);
            //         }
            //     }
            // } else {
            //     // 如果有传递token才验证是否登录状态
            //     if ($token) {
            //         // return false;
            //         // $this->auth->init($token);
            //     }
        }
        parent::initialize();
    }

    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg    提示信息
     * @param mixed $data   返回的数据
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', $data = '', array $header = [])
    {
        $code = 1;
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];

        $type = $this->getResponseType();
        $header['Access-Control-Allow-Origin'] = '*';
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token,Authorization,XX-Api-Version,XX-Wxapp-AppId';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response = Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param mixed $msg    提示信息,若要指定错误码,可以传数组,格式为['code'=>您的错误码,'msg'=>'您的错误消息']
     * @param mixed $data   返回的数据
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($data, $code, $msg, $type, $header);
    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        return 'json';
    }

    protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];

        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }

        $type = $type ?: $this->getResponseType();
        $response = Response::create($result, $type, $code)->header($header);

        throw new HttpResponseException($response);
    }



    public function place_sub($str) 
    { 
        $result = array(); 
        preg_match_all("/(?:\()(.*)(?:\))/i",$str, $result); 
        return $result[1][0]; 
    }

  
     //登录
     public function login_contract_review($cont_data){
        file_put_contents('jindie.log', date('Y-m-d H:i:s').'rse:'.$cont_data.PHP_EOL, FILE_APPEND); 
        libxml_disable_entity_loader(false);
        $client = new \SoapClient("http://10.108.0.52:6888/ormrpc/services/EASLogin?wsdl");//登录
        $getFunctions = $client->__getFunctions(); //获取服务器上提供的方法

        $WSContext = $this->place_sub($getFunctions[3]);
        $substr = explode(",",$WSContext);
        $substr = count($substr);

        if($substr == 6){
             //6个参数
             $res = $client->login("blqjkNew","blqjk123","eas","server","L2",2);
        }elseif($substr == 7){
             //7个参数
             $res = $client->login("blqjkNew","blqjk123","eas","server","L2",2,"BaseDB");
        }elseif($substr == 8){
             //8个参数
             $res = $client->login("blqjkNew","blqjk123","eas","server","L2",2,"BaseDB",0);
        }
        
        $row = $this->newAddContractReview($res->sessionId,$cont_data);
        if(!empty($res->sessionId)){
            $row = $this->newAddContractReview($res->sessionId,$cont_data);
            if($row['msg'] == "success"){
                $wrq = [
                    "code" =>1,
                    'msg'=>"成功",
                    'Serialnum'=>$row['Serialnum']
                ];
            }else{
                $wrq = [
                    "code" =>0,
                    'msg'=>"失败",
                    'Serialnum'=>$row['Serialnum']
                ];
            }
            return $wrq;
        }else{
            $wrq = [
                "code" =>0,
                'msg'=>"失败",
                'Serialnum'=>$res
            ];
            return $wrq;
        }
    }

    
    //合同评审单同步
    public function newAddContractReview($SessionId,$cont_data){
        //$SessionId = "6c143ba5-532b-4f7f-9474-9de4391a74d5";
        libxml_disable_entity_loader(false);
        $client = new \SoapClient("http://10.108.0.52:6888/ormrpc/services/WSContractReviewFacade?wsdl");
        //$array = get_object_vars($result);
 
        // echo('<pre>');
        // dump($client->__getFunctions());die;//获取服务器上提供的方法
         //dump($client->__getTypes());die;//获取服务器上提供的数据类型
        // echo('</pre>');
      
         //设置header格式
         $headerVar = new \SoapVar('<ns1:SessionId xmlns:ns1="http://login.webservice.bos.kingdee.com">'.$SessionId.'</ns1:SessionId>',XSD_ANYXML);
        
         //设置header值
         $header = new \SoapHeader('http://10.108.0.52:6888/ormrpc/services/WSContractReviewFacade?wsdl', 'newAddContractReview',$headerVar);
         $client->__setSoapHeaders(array($header));
         
         //请求接口
         $res = $client->newAddContractReview($cont_data);
       //  dump(json_decode($cont_data)->Serialnum);die;
         $ars = [
             'msg'=>$res,
             'Serialnum'=>json_decode($cont_data)->Serialnum
         ];
         return $ars;
    }
    
      //即时库存登录接口
      public function real_time_inventory_login(){
        libxml_disable_entity_loader(false);
       // $client = new \SoapClient("http://10.108.0.57:8888/ormrpc/services/EASLogin?wsdl");//登录
        $client = new \SoapClient("http://10.108.0.52:6888/ormrpc/services/EASLogin?wsdl");//登录
        $getFunctions = $client->__getFunctions(); //获取服务器上提供的方法
    
        $WSContext = $this->place_sub($getFunctions[3]);
        $substr = explode(",",$WSContext);
        $substr = count($substr);

        if($substr == 6){
             //6个参数
             $res = $client->login("blqjkNew","blqjk123","eas","A02","L2",2);
        }elseif($substr == 7){
             //7个参数
             $res = $client->login("blqjkNew","blqjk123","eas","server","L2",2,"BaseDB");
        }elseif($substr == 8){
             //8个参数
             $res = $client->login("blqjkNew","blqjk123","eas","server","L2",2,"BaseDB",0);
        }
        if(!empty($res->sessionId)){
            $row = $this->queryInventory($res->sessionId);
            if($row['msg']["result"] == "success"){
                $wrq = [
                    "code" =>1,
                    'msg'=>"成功",
                    'data'=>$row['msg']["inventory"]
                ];
            }else{
                $wrq = [
                    "code" =>0,
                    'msg'=>"失败",
                    'data'=>""
                ];
            }
            return $wrq;
        }else{
            $wrq = [
                "code" =>0,
                'msg'=>"失败",
                'data'=>$res
            ];
            return $wrq;
        }
    }

    //获取即时库存数据
    public function queryInventory($SessionId){
        libxml_disable_entity_loader(false);
        $client = new \SoapClient("http://10.108.0.52:6888/ormrpc/services/WSContractReviewFacade?wsdl");
        $jskc_data = [
            "isInit"=>true,
            "materialNums"=>[]
        ];
       $jskc_data = json_encode($jskc_data);
         //设置header格式
         $headerVar = new \SoapVar('<ns1:SessionId xmlns:ns1="http://login.webservice.bos.kingdee.com">'.$SessionId.'</ns1:SessionId>',XSD_ANYXML);
        
         //设置header值
         $header = new \SoapHeader('http://10.108.0.52:6888/ormrpc/services/WSContractReviewFacade?wsdl', 'queryInventory',$headerVar);
         $client->__setSoapHeaders(array($header));
         $jskc_data = [
             "isInit"=>true,
             "materialNums"=>[]
         ];
         $jskc_data = json_encode($jskc_data);
         //请求接口
         $res = $client->queryInventory($jskc_data);
         $inventory = json_decode($res,true);
         $ars = [
             'msg'=>$inventory
         ];
         return $ars;
    }

    
    //根据手机号获取crm用户id
    public function getByMobile($owner_id){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/getByMobile';  // 根据手机号查询员工
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "18394181267";
        $phone = explode(",",$owner_id);
        $sdf = [];
        foreach ($phone as $mobile){
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'mobile'),JSON_UNESCAPED_UNICODE);
        
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
            {
            $sdf[] = $dsdf['empList'][0]["openUserId"];
            }
        }
        return $sdf;
    }

    
    //根据员工昵称获取crm用户id
    public function getByNickName($nickName){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/getByNickName';  // 通过员工昵称查询员工
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "刘兴堂";
        $phone = explode(",",$nickName);
        $sdf = [];
        foreach ($phone as $nickName){
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'nickName'),JSON_UNESCAPED_UNICODE);
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success' && !empty($dsdf['empList']) )
            {
            //$sdf[] = $dsdf['empList'][0]["openUserId"];
                $rst = [
                    "code"=>1,
                    "data"=>$dsdf['empList'][0]["openUserId"]

                ];
            }else{
                $rst = [
                    "code"=>-1,
                    "msg"=>$dsdf["errorDescription"]

                ];
            }
        }
        return $rst;
    }

         //查询人员信息
         public function get_renyuan($owner){
             $qwe = $this->corpAccessToken();
             $url ='https://open.fxiaoke.com/cgi/crm/v2/data/query';  // 根据条件查询人员对象的列表 
             $corpAccessToken = $qwe['corpAccessToken'];   
             $corpId = $qwe['corpId'];
             $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
            
             $sdf = [];
             foreach ($owner as $mobile){
             
                $data = ['dataObjectApiName'=>'PersonnelObj','search_query_info'=>[ 'offset'=>0, 'limit'=>1, 'filters'=>[[ 'field_name'=>'phone','field_values'=>[$mobile],'operator'=>'EQ' ]]]];
                $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
                $method = 'POST';
                $header = [
                                 'Content-Type:application/json'
                        ];
                 $dsdf = $this->http_curl($url,$method, $res, $header);
                
                 if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'OK' )
                 {
                    $sdf[] = $dsdf["data"]["dataList"][0]["field_v86j2__c"];
                 }
             }
             return $sdf;
 
         }
    

     //根据Id查询员工信息
     public function getByopenUserid($owner_id){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/get';  // 根据Id查询员工信息
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "18394181267";
        //$phone = explode(",",$owner_id);
        //$owner_id[1] = "FSUID_C508A03A3F8C43C1155D5816CF702B34";
        $phone = $owner_id;
        $sdf = [];
     
        foreach ($phone as $openUserId){
        
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'openUserId'),JSON_UNESCAPED_UNICODE);
          
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
                
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success')
            {
                $sdf[] = $dsdf['mobile'];//employeeNumber
            }
        }
        return $sdf;
    }

    //根据Id查询员工信息->销售员
    public function getByopenUseridxsy($owner_id){
        $qwe = $this->corpAccessToken();
        $url ='https://open.fxiaoke.com/cgi/user/get';  // 根据Id查询员工信息
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        //$mobile = "18394181267";
        //$phone = explode(",",$owner_id);
        //$owner_id[1] = "FSUID_C508A03A3F8C43C1155D5816CF702B34";
        $phone = $owner_id;
        $sdf = [];
     
        foreach ($phone as $openUserId){
        
            $res =  json_encode(compact('corpAccessToken', 'corpId', 'openUserId'),JSON_UNESCAPED_UNICODE);
          
            $method = 'POST';
            $header = [
                            'Content-Type:application/json'
                        ];
            $dsdf = $this->http_curl($url,$method, $res, $header);
         
            if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorMessage'] == 'success')
            {
                $sdf[] = $dsdf['name'];//employeeNumber
            }
        }
        return $sdf;
    }

       //根据负责人查出负责人邮箱
       public function get_onwer($owner){
        // $id = "18991274097";
         $qwe = $this->corpAccessToken();
         $url ='https://open.fxiaoke.com/cgi/crm/v2/data/query';  // 根据条件查询人员对象的列表 
         $corpAccessToken = $qwe['corpAccessToken'];   
         $corpId = $qwe['corpId'];
         $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
         $data = ['dataObjectApiName'=>'PersonnelObj','search_query_info'=>[ 'offset'=>0, 'limit'=>1, 'filters'=>[[ 'field_name'=>'phone','field_values'=>[$owner],'operator'=>'EQ' ]]]];
         $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        // dump($res);die;
         $method = 'POST';
          $header = [
                        'Content-Type:application/json'
                    ];
         $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
         if(!empty($dsdf) && isset($dsdf) && $dsdf['errorCode'] == '0' && $dsdf['errorDescription'] == 'success' && $dsdf['errorMessage'] == 'OK')
          {
             return $dsdf["data"]["dataList"][0]["email"];
          }else{
             return false; 
          }
     }

      //查询关联销售订单明细行号
    public function sale_order_minxi($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'field_B16bQ__c','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'object_FR2am__c'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
       
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0 &&  !empty($dsdf["data"]["dataList"])){
            return $dsdf["data"]["dataList"][0]["_id"];
        }else{
            return "";
        }
    }

      
    //查询关联合同评审
    public function contract_review($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'name','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'object_qdBZ2__c'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0 &&  !empty($dsdf["data"]["dataList"])){
            return $dsdf["data"]["dataList"][0]["_id"];
        }else{
            return "";
        }
    }

     //查询关联产品名称
     public function contract_Product_Name($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'field_G2HyG__c','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'object_FR2am__c'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0 &&  !empty($dsdf["data"]["dataList"])){
            return $dsdf["data"]["dataList"][0]["_id"];
        }else{
            return "";
        }
    }
   

     //查询销售订单关联
     public function sale_order_num($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'name','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'object_1bq4S__c'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0 &&  !empty($dsdf["data"]["dataList"])){
            return $dsdf["data"]["dataList"][0]["_id"];
        }else{
            return "";
        }
    }

    
    //查询关联客户
    public function gl_customer($name){
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/findOne';
       //   $url = 'https://open.fxiaoke.com/cgi/crm/v2/data/query ';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'name','field_values'=>[$name],'operator'=>'EQ' ]]],'dataObjectApiName'=>'AccountObj'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            return $dsdf["data"]["objectData"]["_id"];
        }else{
            return "";
        }
    }

     /**
     * 获取token
     */
    public function corpAccessToken()
    {
        $method = 'POST';
        $appId = 'FSAID_131aba6';
        $appSecret = '69a6c56e23234bc9b56992f1468d103a';
        $permanentCode = 'F7BE99269E4BFC33400A92D039A3E28F';
        $url = 'https://open.fxiaoke.com/cgi/corpAccessToken/get/V2';
        $header = [
                         'Content-Type:application/json'
                   ];
        $res =  json_encode(compact('appId', 'appSecret', 'permanentCode'));
        $data = $this->http_curl($url,$method, $res, $header, $timeout = 10); 
        
        if(!empty($data) && isset($data) && $data['errorCode'] ==0 && $data['errorMessage'] == 'success' )
        {
            $data['addtime'] = time();
            if(Db::name('atoken')->where('id',1)->find())
            {
               $zxc = Db::name('atoken')->where('id',1)->update($data);  
            }else{
               $zxc = Db::name('atoken')->insert($data);  
            }
           return $data;
        }
        
    }

    /**
    *   post 请求体 头部 封装
    */
    protected function qqtbff($data)
    {
        $qwe = $this->corpAccessToken();
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $res =  compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data');
    //   dump($res);die; 
        return $res;
    }

    /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */   
    protected function htcurl($url, $data = array())
    {
        $method = 'POST';
        $timeout = 10;
        $header = [
                        'Content-Type:application/json'
                    ];
        $curl = curl_init($url);
        $method = strtoupper($method);
        //请求方式啥
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        //post请求
        if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        //超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        //设置header头
        // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
        
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        //返回抓取数据
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //输出header头信息
        curl_setopt($curl, CURLOPT_HEADER, true);
        //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);

        //https请求
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $curlError = curl_error($curl);
        list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
        $status = $status;
        $headerStr = trim(substr($content, 0, $status['header_size']));
        $content = trim(substr($content, $status['header_size']));
        
        $cont = json_decode($content,true);
        
        //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

    }

     /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function http_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);

       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
        
        $cont = json_decode($content,true);
        
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }

    
     
}
